package com.A1908.dao.impl;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.*;

/*
@name:
@description:
@author: lzy
@title: 天王盖地虎!!!
@time:  2021-03-25 08:58:10
*/
public class BaseDao {
    public Connection conn(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        Connection conn=null;
        try {
            conn= DriverManager.getConnection("jdbc:mysql://47.105.188.14:3306/lijin?useUnicode=true&characterEncoding=utf-8", "lijin", "nGwtcYCw7DRc3siX");
            return conn;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public Connection getConnByJNDI(){
        Connection conn=null;
        try {
            Context context = new InitialContext();
            DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/mysql");
            conn=dataSource.getConnection();
            return conn;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public PreparedStatement pstmt(Connection conn,String sql,Object objs[]){

        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            if (objs!=null){
                for (int i=0;i<objs.length;i++){
                    pstmt.setObject(i+1,objs[i]);
                }
            }
            return pstmt;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }//查询用

    public int executeUpdate(String sql, Object [] objs) {
        PreparedStatement pstmt=null;
        Connection conn=conn();
        try {
            pstmt=conn.prepareStatement(sql);
            //绑定参数
            if (objs!=null){
                for (int i=0;i<objs.length;i++){
                    pstmt.setObject(i+1,objs[i]);
                }
            }
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            cloesAll(conn,pstmt,null);
        }
        return 0;
    }//编辑用

    public void cloesAll(Connection conn, Statement stmt, ResultSet rs) {
        if (conn !=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt !=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs !=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
